package com.sikaryofficial.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.domain.ChannelGoodsScopeReq;
import com.sikaryofficial.system.domain.GoodsScope;
import com.sikaryofficial.system.mapper.GoodsScopeMapper;
import com.sikaryofficial.system.service.IGoodsScopeService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 商品范围(用于指定用户可见商品范围)Service业务层处理
 *
 * @author qinjinyuan
 * @date 2024-10-14
 */
@Service
public class GoodsScopeServiceImpl extends ServiceImpl<GoodsScopeMapper, GoodsScope> implements IGoodsScopeService {

    @Override
    @DS("hismk_workbench")
    public Boolean allotGoodsScope(ChannelGoodsScopeReq req) {
        // 删除之前的数据
        this.lambdaUpdate().setSql("  deleted_version = goods_scope_id ")
                .set(GoodsScope::getUpdatedTime, new Date())
                .set(GoodsScope::getUpdatedBy, SecurityUtils.getUserId())
                .eq(GoodsScope::getDeletedVersion, 0L)
                .in(GoodsScope::getUserId, req.getUserIds()).update();
        List<GoodsScope> saveDataList = Lists.newArrayList();

        // 为每一个用户分配商品集合数据
        req.getUserIds().forEach(userId -> req.getGoodsIds().forEach(goodsId -> {
            GoodsScope goodsScope = new GoodsScope();
            saveDataList.add(goodsScope);
            goodsScope.setUserId(userId);
            goodsScope.setGoodsId(goodsId);
            goodsScope.setCreatedBy(SecurityUtils.getUserId());
            goodsScope.setCreatedTime(new Date());
        }));
        return this.saveBatch(saveDataList);
    }
}
